package org.baojie.raft.util.current;

import java.util.List;
import java.util.concurrent.*;

public class RaftSchedPool extends ScheduledThreadPoolExecutor {

    public RaftSchedPool(int core, ThreadFactory factory) {
        super(core, factory);
    }

    public final void shutdown(RaftSchedPool pool) {
        if (null == pool) {
            return;
        } else {
            doShutdown(pool);
        }
    }

    private final void doShutdown(RaftSchedPool pool) {
        pool.shutdown();
        if (pool.isTerminated()) {
            return;
        } else {
            for (int i = 0; i < 100; i++) {
                pool.shutdown();
                if (pool.isTerminated()) {
                    break;
                } else {
                    LocalSleep.park(10, TimeUnit.MILLISECONDS);
                }
            }
            if (!pool.isTerminated()) {
                pool.shutdownNow();
            }
        }
    }

    public final void cancel(List<ScheduledFuture<?>> futures, RaftSchedPool pool) {
        if (null == futures) {
            return;
        } else {
            doCancel(futures, pool);
        }
    }

    private final void doCancel(List<ScheduledFuture<?>> futures, RaftSchedPool pool) {
        for (Future<?> fuc : futures) {
            if (null != fuc) {
                fuc.cancel(true);
                if (null != pool) {
                    pool.purge();
                }
            }
        }
    }

}
